package com.wx.service.impl;

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.wx.core.process.WxApi;
import com.wx.core.vo.Token;
import com.wx.entity.SysWxToken;
import com.wx.model.BussinessException;
import com.wx.service.TokenService;
import com.zyht.common.util.HttpUtils;

/**
 * token
 * @author dingyaming
 */
@Slf4j
@Service
public class TokenServiceImpl implements TokenService {

	@Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
	@Override
	public SysWxToken doWxToken(String wxid,String appId,String appSecret){

		if(StringUtils.isEmpty(appSecret)){
			throw new BussinessException("appSecret 为空");
		}

		Token token = getToken(appId,appSecret);
		if(token == null || token.getErrcode() != null){
			throw new BussinessException("接口获取token失败");
		}

		SysWxToken sysWxTokens = new SysWxToken();
		sysWxTokens.setAccesstoken(token.getAccessToken());
		sysWxTokens.setExpiresin(token.getExpiresIn());
		sysWxTokens.setOpenid(token.getOpenid());
		sysWxTokens.setErrcode(0);
		sysWxTokens.setErrmsg("ok");
		sysWxTokens.setCreated(System.currentTimeMillis());

		return sysWxTokens;
	}

	// 获取接口访问凭证
	private Token getToken(String appId,String appSecret){

		Token token = null;
		String tockenUrl = WxApi.getTokenUrl(appId,appSecret);
		String result = HttpUtils.httpsGet(tockenUrl);
		JSONObject jsonObject = JSONObject.parseObject(result);
		if(null != jsonObject && !jsonObject.containsKey("errcode")){
			token = new Token();
			token.setAccessToken(jsonObject.getString("access_token"));
			token.setExpiresIn(jsonObject.getInteger("expires_in"));
		} else if(null != jsonObject){
			token = new Token();
			token.setErrcode(jsonObject.getInteger("errcode"));
		}
		return token;
	}
}
